<?php
/**
 * Created by PhpStorm.
 * User: 聪
 * Date: 2019/4/14
 * Time: 22:00
 */

namespace app;


use think\Model;

class BaseModel extends Model
{

    const IMG_URL = 'https://zcollar.cn/uploads/';

//    const IMG_URL = 'http://hs.com/uploads/';

    public function cnt($where = false): int
    {
        return $this->where($where)->count();
    }

    public function inc(array $where = [], string $field,$step = 1)
    {
        return $this->where($where)->setInc($field,$step);
    }

    public function saveOne(array $data, array $where = [])
    {
        return $this->save($data, $where);
    }

    public function getValByCol(array $where, string $field)
    {
        return $this->where($where)->value($field);
    }

    public function getOne($where = false, array $with = [],string $orderBy = '')
    {
        return $this->with($with)->where($where)->field($this->allowQuery)->order($orderBy)->find();
    }

//    public function findOrCreate(array $where, string $findField, array $createData)
    public function findOrCreate(array $where, array $createData)
    {
        $findRet = $this->getOne($where);
        if (empty($findRet)) {
            return $this->save($createData);
        }
        return $findRet;
    }

    public function delOne(array $where)
    {
        return $this->where($where)->limit(1)->delete();
    }

    public function allBySelect($limit = false, $where = false, array $with = [], string $orderBy = 'id DESC')
    {
        return $this->with($with)->where($where)->field($this->allowQuery)->limit($limit)->order($orderBy)->select();
    }

    public function allByColumn($limit = false, $where = false, string $orderBy = 'id DESC')
    {
        return $this->where($where)->limit($limit)->order($orderBy)->column($this->allowQuery);
    }

    public function withIn(string $withModel, array $whereIn, array $hidden = [], $where = false, string $orderBy = 'id DESC')
    {
        $field = key($whereIn);
        return $this->with($withModel)->where($where)->whereIn($field, $whereIn[$field])->field($this->allowQuery)->order($orderBy)->select()->hidden([$withModel => $hidden]);
    }

    public function findWith(array $with, array $where = [])
    {
        return $this->with($with)->where($where)->field($this->allowQuery)->find();
    }

    public function allWhereIn(array $whereIn, $where = false, string $orderBy = 'id DESC')
    {
        $field = key($whereIn);
        return $this->where($where)->whereIn($field, $whereIn[$field])->field($this->allowQuery)->order($orderBy)->select();
    }

    public function base_hasMany(array $where, string $withModel)
    {
        return $this->$withModel()->where($where)->select();
    }
}